package com.sd.activity;

import java.lang.reflect.Field;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alex.books.BaseBook;
import com.alex.books.BookPageFactory;
import com.alex.books.BookStore;
import com.alex.books.ReaderingInfo;
import com.alex.database.BookDao;
import com.alex.exception.UnsupportedFormatException;
import com.alex.log.ALog;
import com.mobclick.android.MobclickAgent;
import com.sd.reader.ReaderBook;
import com.sd.reader.ReaderPopWindow;
import com.sd.reader.ReaderSet;
import com.sd.util.LoadingProgressDialog;
import com.sd.view.DialogManager;
import com.sd.view.ToastManager;


public class ReadBookActivity extends BaseActivity implements OnClickListener{
	
	public static String BOOK_ID = "book_id";
	
	public static String READINGINFO = "readinginfo";
	
	private RelativeLayout mReaderScreen;
	private int topBarHeight;
	/**
	 * 书本
	 */
	private BaseBook mBaseBook;
	/**
	 * 阅读器
	 */
	private ReaderBook mReader;
	/**
	 * 标题栏
	 */
	private TextView mTitleTV;
	
	private LayoutInflater mInflater;
	
	private Intent mIntent;
	
	private int mScreenW;
	private int mScreenH;
	private float density;
	
	private int msgWhat = 0;
	private Handler mHandler =  new Handler() { 
		public void handleMessage(Message msg) {  
			
			switch (msg.what) {
			case -1:
				Toast.makeText(ReadBookActivity.this, "不好意思，不支持格式", Toast.LENGTH_SHORT).show();
				break;
			case 0:
				ReaderPopWindow.getInstance().createPopWindow(ReadBookActivity.this, mReader);
				ReaderPopWindow.getInstance().setBaseBook(mBaseBook);
				mReader.setLineSpace(ReaderSet.getInstance().getmFontSize()*density);
				mReader.setReaderTextSize(ReaderSet.getInstance().getmFontSize(),density);
				mReader.setTypeface();
				mReader.nextPage();
				mReader.onFirst();
				break;
			case 1:
				ReaderPopWindow.getInstance().setBaseBook(mBaseBook);
				mReader.setLineSpace(ReaderSet.getInstance().getmFontSize()*density);
				mReader.setReaderTextSize(ReaderSet.getInstance().getmFontSize(),density);
				mReader.setTypeface();
				mReader.reFreshPage();
				break;
			default:
				break;
			}
			LoadingProgressDialog.dismiss();
            super.handleMessage(msg);   
       }   
	};
	
	private class mThread implements Runnable{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				mBaseBook = new BaseBook();
				int bookId = mIntent.getIntExtra(BOOK_ID, 0);
				mBaseBook = BookStore.getInstance().getABook(ReadBookActivity.this, mIntent.getIntExtra(BOOK_ID, 0));
				if(mIntent.getSerializableExtra(READINGINFO) !=null ){
					ReaderingInfo mReaderingInfo = (ReaderingInfo)mIntent.getSerializableExtra(READINGINFO);
					mBaseBook.mReaderingInfo = mReaderingInfo;
				}
				BookPageFactory.getInstance().openBook(ReadBookActivity.this,mBaseBook);
				BookPageFactory.getInstance().setReaderFormat(ReaderSet.getInstance().getmFontSize()*density, 0, mScreenW - 40, mScreenH-40);
				mBaseBook.mBookMarks = BookStore.getInstance().getBookMarks(ReadBookActivity.this, bookId);
				mBaseBook.mChapters = BookStore.getInstance().getChapters(ReadBookActivity.this, bookId);
				ALog.e("size:"+mBaseBook.mBookMarks.size());
				MobclickAgent.onEvent(ReadBookActivity.this, "bookname", mBaseBook.mBookName);
				mHandler.sendEmptyMessage(msgWhat);
			} catch (UnsupportedFormatException e) {
				// TODO Auto-generated catch block
				mHandler.sendEmptyMessage(-1);
				e.printStackTrace();
			}
			
		}
	}
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_reader);

        Class<?> c = null;
        Object obj = null;
        Field field = null;
        int x = 0;
        try {
        	c = Class.forName("com.android.internal.R$dimen");
        	obj = c.newInstance();
        	field = c.getField("status_bar_height");
        	x = Integer.parseInt(field.get(obj).toString());
        	topBarHeight = getResources().getDimensionPixelSize(x);
        } catch (Exception e1) {
	          e1.printStackTrace();
        } 
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        mScreenW = metric.widthPixels;  // 屏幕宽度（像素）
        mScreenH = metric.heightPixels;  // 屏幕高度（像素）
        density = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）
        
        mIntent = this.getIntent();
        
        initFindView();
        initReaderSet();
        fullScreen();
        changeReadModel();
	}
	
	/**
	 * 初始化设置
	 */
	private void initReaderSet(){
		
		 isYe = ReaderSet.getInstance().getReadModel();
	     
	     WindowManager.LayoutParams lp = ReadBookActivity.this.getWindow().getAttributes();  
	 	 lp.screenBrightness = Float.valueOf(ReaderSet.getInstance().getBrightness()) *1 / 255;
	 	 this.getWindow().setAttributes(lp); 
	 	 msgWhat = 0;
	     initBookPageFactory();
	}
	
	/**
	 * 初始化
	 */
	private void initFindView(){
		mInflater = LayoutInflater.from(this);
		
		mReaderScreen = (RelativeLayout)findViewById(R.id.readerscreen);
		mReader = (ReaderBook)findViewById(R.id.reader);
	    mReader.setOnSingleTapUpListener(this);
		
		mReader.init(mScreenW, mScreenH, density);
	}

	
	@Override
	protected void onNewIntent(Intent intent) {
		mIntent = intent;
		// TODO Auto-generated method stub
		msgWhat = 1;
		initBookPageFactory();
	}
	
	public void onNewIntent0(Intent intent){
		mIntent = intent;
		// TODO Auto-generated method stub
		msgWhat = 1;
		initBookPageFactory();
	}
	

	@Override
	protected void onPause() {
		// TODO Auto-generated method stubd
		mBaseBook.mLastTime = ""+System.currentTimeMillis();
		mBaseBook.mBookMarksNumber = BookStore.getInstance().getBookMarks(this, mBaseBook.mBookId).size();
		BookDao.getInstance().updateBook(this, mBaseBook);
		ReaderSet.getInstance().commitReaderSet();
		if(!isFullScreen){
			fullScreen();
		}
		super.onPause();
	}
	

	private void initBookPageFactory(){
		LoadingProgressDialog.show(this, R.string.msg_loading);
		new Thread(new mThread()).start();
	}
	
	private boolean isYe = true;
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int v_id = v.getId();
		switch (v_id) {
		case R.id.reader:
			//点击阅读中
			noFullScreen();
			break;
		case R.id.btn_return:
			finish();
			break;
		case R.id.btn_bookmark:
			ToastManager.getInstance().showText(this, R.string.msg_success_mark);
			String text = mBaseBook.mReaderingInfo.mCurText;
			if(text.length()>20){
				text = text.substring(20);
			}
			BookStore.getInstance().addBookMark(this, mBaseBook,text);
			break;
		case 0:
			fullScreen();
			break;

		default:
			break;
		}
	}
	private boolean isFullScreen = true;
	
	private void fullScreen(){
		
		isFullScreen = true;
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
		RelativeLayout.LayoutParams l0 = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
		l0.topMargin = topBarHeight;
		RelativeLayout.LayoutParams l = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
		l.topMargin = 0;
		mReaderScreen.setLayoutParams(l);
		ReaderPopWindow.getInstance().dimss();
	}
	
	
	private void noFullScreen(){
		ReaderPopWindow.getInstance().getpop().showAtLocation(mReaderScreen, Gravity.BOTTOM, 0,0);
		isFullScreen = false;
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
	    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		RelativeLayout.LayoutParams l = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
		l.topMargin = -topBarHeight;
		mReaderScreen.setLayoutParams(l);
	}
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		// TODO Auto-generated method stub
		if(event.getKeyCode() ==KeyEvent.KEYCODE_MENU
				&& event.getAction() == KeyEvent.ACTION_DOWN){
			if(isFullScreen){
				noFullScreen();
			}else{
				fullScreen();
			}
		}
		return super.dispatchKeyEvent(event);
	}
	
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		mReader.destory();
		super.onDestroy();
	}

	
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
	}
	private void changeReadModel() {

		ReaderSet.getInstance().setReadModel(isYe);

		if (isYe) {
			// 夜间模式
			mReader.setReaderBg(R.drawable.wallpaper7, 0xffffffff);
			isYe = false;
		} else {
			// 普通模式
			mReader.setReaderBg(ReaderSet.getInstance().getReadBg(), ReaderSet
					.getInstance().getFontColor());
			isYe = true;
		}

	}
	
}
